package com.ruoyi.table.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.ruoyi.table.mapper.TableMapper;
import com.ruoyi.table.model.dto.TableDTO;
import com.ruoyi.table.model.qo.PageResult;
import com.ruoyi.table.service.ITableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Author ChenYuCong
 * @Date 2022/9/26
 * @Description
 * @since 1.0
 */
@Service
@Slf4j
public class TableServiceImpl implements ITableService {

    @Autowired
    TableMapper tableMapper;


    @Override
    public void updateBySql(String sql) {
        //log.info("updateBySql:"+sql);
        tableMapper.updateBySql(sql);
    }

    @Override
    public Long insertBySql(TableDTO tableDTO) {
        //log.info("insertBySql:"+tableDTO.getSql());
        tableMapper.insertBySql(tableDTO);
        return tableDTO.getId();
    }

    @Override
    public void updateBySql(String sql, Object[] params) {
        String sqlStr = convertSql(sql, params);
        //log.info("updateBySql:"+sqlStr);
        tableMapper.updateBySql(sqlStr);
    }
    @Override
    public void insertBySql(String sql, Object[] params) {
        String sqlStr = convertSql(sql, params);
        //log.info("insertBySql:"+sqlStr);
        tableMapper.updateBySql(sqlStr);
    }
    @Override
    public Long insertBySql(TableDTO tableDTO, Object[] params) {
        String sqlStr = convertSql(tableDTO.getSql(), params);
        tableDTO.setSql(sqlStr);
        //log.info("insertBySql:"+sqlStr);
        tableMapper.insertBySql(tableDTO);
        return tableDTO.getId();
    }

    @Override
    public List<Map<String, Object>> selectBySql(String sql, Object[] params) {
        String sqlStr = convertSql(sql, params);
        //log.info("selectBySql:"+sqlStr);
        List<Map<String, Object>> result = tableMapper.selectBySql(sqlStr);
        return result;
    }

    @Override
    public Map<String, Object> selectBySqlFirst(String sql, Object[] params) {
        List<Map<String, Object>> result = tableMapper.selectBySql(convertSql(sql, params));
        if(result!=null && result.size()>0){
            return result.get(0);
        }
        return null;
    }

    @Override
    public PageResult<Map<String, Object>> selectPageBySql(String sql, Object[] params, int pageNum, int pageSize) {
        PageResult<Map<String, Object>> page = new PageResult<>();
        // 查询总条数
        int count = selectCountBySql(sql, params);
        pageSize = pageSize == 0 ? 20 : pageSize;
        int offset=(pageNum -1) * pageSize;
        offset = Math.max(offset, 0);
        page.setTotal(count);
        if (count > 0) {
            // 查询数据
            String sqlStr = convertSql(sql, params);
            List<Map<String, Object>> result = tableMapper.selectBySql("SELECT * from (" + sqlStr + ") a limit " + offset + "," + pageSize);
            page.setData(result);
        }
        return page;
    }

    @Override
    public int selectCountBySql(String sql, Object[] params) {
        String sqlStr = convertSql(sql, params);
        return tableMapper.selectCountBySql("SELECT count(*) as num from (" + sqlStr + ") a ");
    }
    @Override
    public int selectCountBySql(String sql) {
        return tableMapper.selectCountBySql("SELECT count(*) as num from (" + sql + ") a ");
    }


    /**
     * 替换SQL 的 ?
     *
     * @param sql    sql
     * @param params params
     * @return Sql
     */
    protected String convertSql(String sql, Object[] params) {
        int i = 0;
        if (params != null && params.length > 0) {
            while (sql.contains(StringPool.QUESTION_MARK)) {
                if (params[i] != null) {
                    if (params[i] instanceof Integer || params[i] instanceof BigDecimal || params[i] instanceof Long) {
                        sql = replaceFirst(sql, StringPool.QUESTION_MARK, params[i] + "");
                    } else {
                        sql = replaceFirst(sql, StringPool.QUESTION_MARK, "'" + params[i] + "'");
                    }
                } else {
                    throw new RuntimeException("sql参数字段不匹配");
                }
                i++;
            }
        }
        return sql;
    }


    public static String replaceFirst(String s, String sub, String with) {
        int i = s.indexOf(sub);
        if (i == -1) {
            return s;
        }
        return s.substring(0, i) + with + s.substring(i + sub.length());
    }
}
